import { MinusCircleFilled, PlusCircleFilled } from "@ant-design/icons";
import type { RedisClient } from "@linksaas-minapp/redis-proxy-api"
import { Button, Form, Input, InputNumber, Modal, Space, Tabs, message } from "antd";
import { useState } from "react";
import { v4 as uuidv4 } from 'uuid';


interface SetValueItem {
    id: string;
    key: string;
}

interface SortedSetValueItem {
    id: string;
    key: string;
    score: number;
}

interface HashValueItem {
    id: string;
    key: string;
    value: string;
}

interface ListValueItem {
    id: string;
    value: string;
}

export interface AddKeyModalProps {
    client: RedisClient | null;
    onCancel: () => void;
    onOk: (newAddKey: string) => void;
}

function AddKeyModal(props: AddKeyModalProps) {
    const [activeKey, setActiveKey] = useState("str");

    const [newKey, setNewKey] = useState("");

    const [strValue, setStrValue] = useState("");
    const [setValueList, setSetValueList] = useState<SetValueItem[]>([
        {
            id: uuidv4(),
            key: "",
        }
    ]);
    const [sortedSetValueList, setSortedSetValueList] = useState<SortedSetValueItem[]>([
        {
            id: uuidv4(),
            key: "",
            score: 0.0,
        }
    ]);
    const [hashValueList, setHashValueList] = useState<HashValueItem[]>([
        {
            id: uuidv4(),
            key: "",
            value: "",
        }
    ]);
    const [listValueList, setListValueList] = useState<ListValueItem[]>([
        {
            id: uuidv4(),
            value: "",
        }
    ]);

    const addSetValueItem = (id: string) => {
        const newList = [] as SetValueItem[];
        for (const item of setValueList) {
            newList.push(item);
            if (item.id == id) {
                newList.push({
                    id: uuidv4(),
                    key: "",
                });
            }
        }
        setSetValueList(newList);
    };

    const addSortedSetItem = (id: string) => {
        const newList = [] as SortedSetValueItem[];
        for (const item of sortedSetValueList) {
            newList.push(item);
            if (item.id == id) {
                newList.push({
                    id: uuidv4(),
                    key: "",
                    score: 0.0,
                });
            }
        }
        setSortedSetValueList(newList);
    };

    const addHashItem = (id: string) => {
        const newList = [] as HashValueItem[];
        for (const item of hashValueList) {
            newList.push(item);
            if (item.id == id) {
                newList.push({
                    id: uuidv4(),
                    key: "",
                    value: "",
                });
            }
        }
        setHashValueList(newList);
    };

    const addListItem = (id: string) => {
        const newList = [] as ListValueItem[];
        for (const item of listValueList) {
            newList.push(item);
            if (item.id == id) {
                newList.push({
                    id: uuidv4(),
                    value: "",
                });
            }
        }
        setListValueList(newList);
    };

    const addData = async () => {
        if (props.client == null) {
            return;
        }
        try {
            const res = await props.client.coreCommand().exists(newKey);
            if (res === 1) {
                message.warning(`${newKey}已经存在`);
                return;
            }
            if (activeKey == "str") {
                await props.client.strCommand().set(newKey, strValue);
            } else if (activeKey == "set") {
                await props.client.setCommand().sadd(newKey, setValueList.map(item => item.key));
            } else if (activeKey == "zset") {
                await props.client.sortedSetCommand().zadd(newKey, sortedSetValueList.map(item => ({
                    value: item.key,
                    score: item.score,
                })));
            } else if (activeKey == "hash") {
                await props.client.hashCommand().hset(newKey, hashValueList.map(item => ({
                    field: item.key,
                    value: item.value,
                })));
            } else if (activeKey == "list") {
                await props.client.listCommand().lpush(newKey, listValueList.map(item => item.value));
            }
            message.info("增加数据成功");
            props.onOk(newKey);
        } catch (e) {
            message.error(`${e}`);
        }
    };

    return (
        <Modal title="增加数据" open
            okText="增加" okButtonProps={{ disabled: newKey.trim() == "" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                addData();
            }}>
            <Form>
                <Form.Item label="Key">
                    <Input value={newKey} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setNewKey(e.target.value);
                    }} />
                </Form.Item>
                <Form.Item label="Value">
                    <Tabs activeKey={activeKey} type="card" onChange={key => setActiveKey(key)}>
                        <Tabs.TabPane key="str" tab="字符串">
                            <div style={{ height: "calc(100vh - 400px)", overflowY: "auto" }}>
                                <Input value={strValue} onChange={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setStrValue(e.target.value);
                                }} />
                            </div>
                        </Tabs.TabPane>
                        <Tabs.TabPane key="set" tab="集合">
                            <div style={{ height: "calc(100vh - 400px)", overflowY: "auto" }}>
                                {setValueList.map(item => (
                                    <div key={item.id} style={{ display: "flex", marginBottom: "10px" }}>
                                        <Input style={{ flex: 1 }} value={item.key} onChange={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            const tmpList = setValueList.slice();
                                            const index = tmpList.findIndex(tmpItem => tmpItem.id == item.id);
                                            if (index != -1) {
                                                tmpList[index].key = e.target.value;
                                                setSetValueList(tmpList);
                                            }
                                        }} />
                                        <Space style={{ marginLeft: "20px" }}>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                addSetValueItem(item.id);
                                            }}><PlusCircleFilled style={{ fontSize: "20px" }} /></Button>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} disabled={setValueList.length <= 1}
                                                onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    setSetValueList(setValueList.filter(tmpItem => tmpItem.id != item.id));
                                                }}><MinusCircleFilled style={{ fontSize: "20px" }} /></Button>
                                        </Space>
                                    </div>
                                ))}
                            </div>
                        </Tabs.TabPane>
                        <Tabs.TabPane key="zset" tab="有序集合">
                            <div style={{ height: "calc(100vh - 400px)", overflowY: "auto" }}>
                                {sortedSetValueList.map(item => (
                                    <div key={item.id} style={{ display: "flex", marginBottom: "10px" }}>
                                        <Input style={{ flex: 1 }} placeholder="值:" value={item.key} onChange={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            const tmpList = sortedSetValueList.slice();
                                            const index = tmpList.findIndex(tmpItem => tmpItem.id == item.id);
                                            if (index != -1) {
                                                tmpList[index].key = e.target.value;
                                                setSortedSetValueList(tmpList);
                                            }
                                        }} />
                                        <InputNumber style={{ flex: 1, marginLeft: "20px" }} placeholder="分数:" precision={5} value={item.score} controls={false}
                                            onChange={value => {
                                                if (value != null) {
                                                    const tmpList = sortedSetValueList.slice();
                                                    const index = tmpList.findIndex(tmpItem => tmpItem.id == item.id);
                                                    if (index != -1) {
                                                        tmpList[index].score = value as number;
                                                        setSortedSetValueList(tmpList);
                                                    }
                                                }
                                            }} />
                                        <Space style={{ marginLeft: "20px" }}>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                addSortedSetItem(item.id);
                                            }}><PlusCircleFilled style={{ fontSize: "20px" }} /></Button>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} disabled={sortedSetValueList.length <= 1}
                                                onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    setSortedSetValueList(sortedSetValueList.filter(tmpItem => tmpItem.id !== item.id));
                                                }}><MinusCircleFilled style={{ fontSize: "20px" }} /></Button>
                                        </Space>
                                    </div>
                                ))}
                            </div>
                        </Tabs.TabPane>
                        <Tabs.TabPane key="hash" tab="哈希表">
                            <div style={{ height: "calc(100vh - 400px)", overflowY: "auto" }}>
                                {hashValueList.map(item => (
                                    <div key={item.id} style={{ display: "flex", marginBottom: "10px" }}>
                                        <Input style={{ flex: 1 }} placeholder="键:" value={item.key} onChange={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            const tmpList = hashValueList.slice();
                                            const index = tmpList.findIndex(tmpItem => tmpItem.id == item.id);
                                            if (index != -1) {
                                                tmpList[index].key = e.target.value;
                                                setHashValueList(tmpList);
                                            }
                                        }} />
                                        <Input style={{ flex: 1, marginLeft: "20px" }} placeholder="值:" value={item.value} onChange={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            const tmpList = hashValueList.slice();
                                            const index = tmpList.findIndex(tmpItem => tmpItem.id == item.id);
                                            if (index != -1) {
                                                tmpList[index].value = e.target.value;
                                                setHashValueList(tmpList);
                                            }
                                        }} />
                                        <Space style={{ marginLeft: "20px" }}>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                addHashItem(item.id);
                                            }}><PlusCircleFilled style={{ fontSize: "20px" }} /></Button>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} disabled={hashValueList.length <= 1}
                                                onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    setHashValueList(hashValueList.filter(tmpItem => tmpItem.id !== item.id));
                                                }}><MinusCircleFilled style={{ fontSize: "20px" }} /></Button>
                                        </Space>
                                    </div>
                                ))}
                            </div>
                        </Tabs.TabPane>
                        <Tabs.TabPane key="list" tab="列表">
                            <div style={{ height: "calc(100vh - 400px)", overflowY: "auto" }}>
                                {listValueList.map(item => (
                                    <div key={item.id} style={{ display: "flex", marginBottom: "10px" }}>
                                        <Input style={{ flex: 1 }} value={item.value} onChange={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            const tmpList = listValueList.slice();
                                            const index = tmpList.findIndex(tmpItem => tmpItem.id == item.id);
                                            if (index != -1) {
                                                tmpList[index].value = e.target.value;
                                                setListValueList(tmpList);
                                            }
                                        }} />
                                        <Space style={{ marginLeft: "20px" }}>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                addListItem(item.id);
                                            }}><PlusCircleFilled style={{ fontSize: "20px" }} /></Button>
                                            <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} disabled={listValueList.length <= 1}
                                                onClick={e => {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    setListValueList(listValueList.filter(tmpItem => tmpItem.id !== item.id));
                                                }}><MinusCircleFilled style={{ fontSize: "20px" }} /></Button>
                                        </Space>
                                    </div>
                                ))}
                            </div>
                        </Tabs.TabPane>
                    </Tabs>
                </Form.Item>
            </Form>
        </Modal>
    );
}

export default AddKeyModal;